package word;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.data.*;
import com.deepoove.poi.data.style.BorderStyle;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * @Author: DRevelation
 * @Date: 2021/8/26 10:06
 */
public class Java2Word {
    public static void main(String[] args) throws IOException {
        XWPFTemplate.compile("src/main/java/word/template.docx").render(new HashMap<String, Object>() {{
            put("title", "我想当帮女郎第二季 （凭证随机码：6547-1093-711）");
            // 一个2行2列的表格
            String url = "https://ahtv-obs.obs.cn-north-4.myhuaweicloud.com/ahtv-obs/20210825/e742351b-fe64-4f3d-55bf-7726dcd18604.jpg";

//            put("table0", Tables.of(new String[][]{
//                    new String[]{"00", "01"},
//                    new String[]{"10", "11"}
//            }).border(BorderStyle.DEFAULT).create());

            BorderStyle borderStyle = new BorderStyle();
            borderStyle.setColor("A6A6A6");
            borderStyle.setSize(4);
            borderStyle.setType(XWPFTable.XWPFBorderType.SINGLE);

            JSONObject obj = new JSONObject(true);
            obj.put("姓名", "江德华");
            obj.put("年龄", "24");
            obj.put("电话号码", "18255656762");
            obj.put("证件照", url);

            LinkedHashMap<String, String> jsonMap1 = JSON.parseObject(obj.toString(), new TypeReference<LinkedHashMap<String, String>>() {
            });

            TableRenderData table = Tables.ofA4MediumWidth().border(borderStyle).center().create();
            for (String key : jsonMap1.keySet()) {
                String value = jsonMap1.get(key);
                ParagraphRenderData paragraph = Paragraphs.of().addText(key).create();
                CellRenderData cell = Cells.of().addParagraph(paragraph).create();
                ParagraphRenderData paragraph2;

                if (value.startsWith("http")) {
                    PictureRenderData picture = Pictures.ofUrl(url).size(150, 200).center().create();
                    paragraph2 = Paragraphs.of().addPicture(picture).create();

                } else {
                    paragraph2 = Paragraphs.of().addText(value).create();
                }
                CellRenderData cell2 = Cells.of().addParagraph(paragraph2).create();
                RowRenderData row = Rows.of().addCell(cell).addCell(cell2).create();
                table.addRow(row);
            }
            put("table0", table);

        }}).writeToFile("src/main/java/word/out_template.docx");
    }
}
